﻿using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;

namespace CodeContrib
{
	public static class XmlExtensions
	{
		public static XDocument RemoveEmptyNamespaces(this XDocument doc, XNamespace defaultNamespace)
		{
			Guard.NotNull(defaultNamespace, "defaultNamespace");

			foreach (var element in doc.Root.DescendantsAndSelf())
			{
				if (string.IsNullOrEmpty(element.Name.Namespace.NamespaceName))
				{
					element.Name = defaultNamespace + element.Name.LocalName;
				}
			}

			return doc;
		}

		public static string RemoveXmlTagWhitespace(this string xml)
		{
			return Regex.Replace(xml.Trim(), @"(?<startTag>[>|<!\[CDATA\[])\s*(?<finishTag>[<|\]\]>])", "${startTag}${finishTag}", RegexOptions.Compiled | RegexOptions.Multiline);
		}

		public static string RemoveXmlTags(this string value)
		{
			return Regex.Replace(value, RegularExpressions.XmlTag, string.Empty, RegexOptions.Compiled | RegexOptions.Multiline).Trim();
		}

		public static string ToXmlString(this XDocument document, Encoding encoding)
		{
			var xml = new StringBuilder();

			using (var stringWriter = new StringWriterWithEncoding(xml, encoding))
			{
				using (var xmlTextWriter = new XmlTextWriter(stringWriter))
				{
					document.Save(xmlTextWriter);
				}
			}

			return xml.ToString();
		}
	}
}